<script setup name="BusinessTemplate">
import { View } from '@element-plus/icons-vue'
import Message from 'vue-m-message'
import businessTemplateService from '@/api/businessTemplate/index.js'
import BaseForm from '@/components/BaseForm/BaseForm.vue'
import Toolbar from '@/components/Toolbar/Toolbar.vue'
import { deepClone, tableCheckChane, uniqueString } from '@/utils/index.js'

const { proxy } = getCurrentInstance()
const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
const ids = ref([])
const tableData = ref([])
const tableColumn = reactive([
  {
    type: 'checkbox',
    width: 50,
    align: 'center',
  },
  {
    type: 'seq',
    width: 50,
    align: 'center',
  },
  {
    field: 'templateName',
    title: '业务模板名称',
    align: 'center',
  },
  {
    title: '归属业务',
    field: 'businessId',
    align: 'center',
    slots: {
      default: 'businessesId',
    },
  },
  {
    title: '操作',
    align: 'center',
    field: 'action',
    slots: {
      default: 'actions',
    },
    fixed: 'right',
    minWidth: 30,
  },
])
const searchConfig = reactive([
  {
    label: '业务模板名称',
    field: 'templateName',
    type: 'input',
  },
])
const queryParam = ref({})
const queryBeforeInsertList = ref([])
const updateFormList = reactive([
  {
    label: '业务模板名称',
    field: 'templateName',
    type: 'input',
    rules: [
      { required: true, message: '请输入业务模板名称', trigger: 'blur' },
    ],
    span: 24,
  },
  {
    label: '归属业务',
    field: 'businessId',
    type: 'cascader',
    props: {
      value: 'businessType',
      label: 'businessTypeName',
      multiple: true,
    },
    rules: [
      { required: true, message: '请选择归属业务', trigger: 'change' },
    ],
    span: 24,
    options: {
      data: queryBeforeInsertList,
    },
  },
])
const updateFormData = ref({})
const dialogVisible = ref(false)
const isView = ref(false)
onMounted(async () => {
  await handleGetQueryBeforeInsert()
  getList()
})

function getList() {
  const params = {
    ...queryParam.value,
    pageNum: pagerConfig.value.currentPage,
    pageSize: pagerConfig.value.pageSize,
  }
  businessTemplateService.list(params).then((res) => {
    if (res.code === 200) {
      tableData.value = res.rows
    }
    pagerConfig.value.total = res.total
  })
}

async function handleAdd() {
  handleGetQueryBeforeInsert()
  dialogVisible.value = true
}

function handleGetQueryBeforeInsert() {
  businessTemplateService.queryBeforeInsert().then((res) => {
    if (res.code === 200) {
      queryBeforeInsertList.value = res.data
    }
  })
}
function handleDelete(row) {
  const delId = row ? row.templateId : ids.value.join(',')
  businessTemplateService.del(delId).then((res) => {
    if (res.code === 200) {
      Message.success('删除成功')
      getList()
    }
  })
}
function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange(data) {
  ids.value = tableCheckChane(data, 'templateId', ids.value)
}

function handleExport() {
  proxy.download('system/businessTemplate/export', { ...queryParam.value, exportIds: ids.value.join(',') }, `businessTemplate__${new Date().getTime()}.xlsx`)
}

function handleSearch(params) {
  queryParam.value = params
  pagerConfig.value.currentPage = 1
  getList()
}

function handleSubmit(formData) {
  const params = {
    ...formData,
    businessId: formData.businessId.map(id => `${id[0]}.${id[1]}`).join(','),
  }
  console.log(params)
  if (formData.templateId) {
    businessTemplateService.update(params).then((res) => {
      if (res.code === 200) {
        Message.success('修改成功')
        dialogVisible.value = false
        handleReset()
        getList()
      }
    })
  }
  else {
    businessTemplateService.add(params).then((res) => {
      if (res.code === 200) {
        Message.success('新增成功')
        dialogVisible.value = false
        handleReset()
        getList()
      }
    })
  }
}

async function handleActionTable(row, type) {
  handleGetQueryBeforeInsert()

  const data = deepClone(row)
  dialogVisible.value = true
  isView.value = type === 'view'
  updateFormData.value = data
  updateFormData.value.businessId = data.businessId?.split(',').map(item => item.split('.'))
}

function handleReset() {
  isView.value = false
  dialogVisible.value = false
  updateFormData.value = {}
}

function handleActionBusinessId(row) {
  const data = deepClone(row)
  const findType = data.businessId?.split(',').map(Number).map(Math.floor)
  const findName = findType.map((type) => {
    // 找到类型匹配的项
    const item = queryBeforeInsertList.value.find(item => item.businessType === type.toString())
    return item ? item.businessTypeName : null
  }).filter(name => name !== null) // 过滤掉未找到的项
  return uniqueString(findName.join(','))
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="">
      <SearchBar :search-config="searchConfig" @search="handleSearch" />
    </el-card>
    <el-card shadow="never" class="mt-2">
      <Toolbar>
        <el-button
          v-hasPermi="['system:businessTemplate:add']"
          type="primary"
          class="el-gradient-primary"
          @click="handleAdd"
        >
          新增
          <el-icon class="el-icon--right">
            <CirclePlusFilled />
          </el-icon>
        </el-button>
        <el-button
          v-hasPermi="['system:businessTemplate:remove']"
          type="danger"
          class="el-gradient-danger"
          :disabled="ids.length === 0"
          @click="handleDelete(null)"
        >
          删除
          <el-icon class="el-icon--right">
            <Delete />
          </el-icon>
        </el-button>
        <el-button
          v-hasPermi="['system:businessTemplate:export']"
          type="warning"
          class="el-gradient-warning"
          @click="handleExport()"
        >
          导出
          <el-icon class="el-icon--right">
            <FolderAdd />
          </el-icon>
        </el-button>
      </Toolbar>
      <vxe-grid
        :row-config="{
          keyField: 'templateId',
        }"
        :data="tableData"
        :columns="tableColumn"
        :pager-config="pagerConfig"
        header-cell-class-name="headerCellClass"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
        max-height="650px"
      >
        <template #businessesId="{ row }">
          {{ handleActionBusinessId(row) }}
        </template>
        <template #actions="{ row }">
          <el-button
            v-hasPermi="['system:businessTemplate:query']"
            size="small"
            text
            type="info"
            @click="handleActionTable(row, 'view')"
          >
            查看
          </el-button>
          <el-button
            v-hasPermi="['system:businessTemplate:edit']"
            size="small"
            text
            type="primary"
            @click="handleActionTable(row, 'update')"
          >
            修改
          </el-button>
          <span v-hasPermi="['system:businessTemplate:remove']">
            <el-popconfirm
              title="确认删除该业务模板？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  size="small"
                  text
                  type="danger"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </span>
        </template>
      </vxe-grid>
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      class="custom-dialog"
      width="36%"
      :destroy-on-close="true"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            {{ updateFormData.templateId ? isView ? '查看' : '修改' : '新增' }}业务模板管理
          </span>
        </div>
      </template>
      <BaseForm
        :field-list="updateFormList"
        :model="updateFormData"
        :options="{
          disabled: isView,
          labelWidth: '110px',
        }"
        @submit="handleSubmit"
        @cancel="handleReset"
      />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.custom-dialog{
  .dialog-header{
    width: 188px;
  }
}
</style>
